package com.example.blackmarket.module.RegisterAndLogin;

import android.os.Handler;
import android.util.Log;

import com.example.blackmarket.callback.IShopCallback;
import com.example.blackmarket.entities.SuccessResponse;
import com.example.blackmarket.model.BlackMarketApi;
import com.example.blackmarket.module.Base.BasePresenter;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

class RegisterPresenter extends BasePresenter<RegisterView> implements IShopCallback {
    private Handler mHandler;

    public RegisterPresenter(RegisterView registerView) {
        attachView(registerView);
        mHandler = new Handler();
    }

    public void getVerifyCode(String mail) {
        BlackMarketApi.getVerifyCode(mail, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.post(() -> onFail(e.toString()));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("注册", "邮箱发送");
                getView().clickVerify();
            }
        });
    }

    public void register(String studentNumber, String password, String confirmPassword, String mail, String verifyCode){
        BlackMarketApi.register(studentNumber, password, confirmPassword, mail, verifyCode, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onFail(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    assert response.body() != null;
                    String data = response.body().string();
                    mHandler.post(() -> onSuccess(data));
                }
                else {
                    assert response.body() != null;
                    String msg = "code: "+ response.code() + " body: " +response.body().string();
                    Log.e("response failure",msg);
                    mHandler.post(()->onFail(msg));
                }
            }
        });
    }


    //callback
    @Override
    public void onSuccess(Object data) {
        SuccessResponse successResponse = new Gson().fromJson(((String)data), SuccessResponse.class);
        this.getView().showSuccess(successResponse);
    }

    @Override
    public void onFail(String msg) {
        this.getView().showFailure(msg);
    }

    @Override
    public void onError() {

    }

    @Override
    public void onComplete() {

    }
}


